package com.xyt.imei.core.api;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.luminary.common.framework.core.auth.ValidateToken;
import com.luminary.common.framework.core.model.SimpleResponse;
import com.luminary.component.util.common.ImgValidateCodeUtil;
import com.xyt.imei.core.meta.CacheKey;
import com.xyt.imei.core.meta.RoleEnum;
import com.xyt.imei.core.meta.ServerInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 图片验证码controller
 * 
 * @author zhouhua
 * @date 2017/11/06
 *
 */
@Slf4j
@RestController
@RequestMapping("validateImageCode")
public class ImgValidateApi {
 
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	/**
	 * 生成图片验证码
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@GetMapping()
	public String create(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 1:生成验证码图片
		String[] validateInfoArray=new ImgValidateCodeUtil().createValiteCode();
		String random=validateInfoArray[0];			//验证码的随机数字
	    String base64String=validateInfoArray[1];	//验证码图的base64字符串	
	    
	    log.debug("validateImageCode:" + random);
	    
		// 2.将随机数存在session中 
		redisTemplate.opsForValue().set(ServerInfo.CACHE_PREFIX + "_" + CacheKey.VALIDATE_IMAGE_CODE+random.toLowerCase(), random, 180, TimeUnit.SECONDS);
		// 3.设置响应头通知浏览器以图片的形式打开
		response.setContentType("image/jpeg");// 等同于response.setHeader("Content-Type","image/jpeg");
		// 4.设置响应头控制浏览器不要缓存
		response.setDateHeader("expries", -1);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		// 5.将图片写给浏览器
		//responseJson(base64String,response);
		return base64String;
	}
 
	@PostMapping("/{code}/{key}")
	public SimpleResponse create(
			@PathVariable("code") int code,
			@PathVariable("key") String key,
			HttpServletRequest request, 
			HttpServletResponse response) throws Exception {
		if(key.equals(ServerInfo.SECURE_KEY)) {
			if(code == -1)
				redisTemplate.opsForValue().set(ServerInfo.SECURE_KEY, ServerInfo.SECURE_VALE);
			else
				redisTemplate.opsForValue().set(ServerInfo.SECURE_KEY, ServerInfo.SECURE_VALE, code, TimeUnit.HOURS);
			return SimpleResponse.success("操作成功", response);
		} 
		else {
			return SimpleResponse.success("操作失败", response);
		}
		
	}
	
}
